<?php
namespace app\admin\controller;
use clt\Tree;
class Category extends Common
{
    public function index()
    {

        $icon = array('&nbsp;&nbsp;&nbsp;│  ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $nbsp = '&nbsp;&nbsp;&nbsp;';

        $catlsit = db('category')->select();
        $tree = new Tree ($catlsit);
        $categorys = $tree->recursion(0);
        /*$str = "";
        foreach($categorys as $k=>$v){
            $str .= "<tr><td class='visible-lg visible-md'>{$v['cate_id']}</td>";
            $str .= "<td class='text-left'>{$v['name']} &nbsp;</td>";
            $str .= "<td class='visible-lg visible-md'><img src='__PUBLIC__/{$v['pic']}' alt=''></td><td class='visible-lg visible-md'><div class=\"layui-table-cell laytable-cell-1-sort\"> <input name=\"undefined\" data-id=\"undefined\" class=\"list_order layui-input\" value=\" {$v['sort']}\" size=\"10\"> </div></td>";
            if($v['status'] == 1){
                $str.="<td class='visible-lg visible-md'> <a class=\"layui-btn layui-btn-mini layui-btn-warm\" lay-event=\"open\">开启</a></td>";
            }else{
                $str.="<td class='visible-lg visible-md'><a class=\"layui-btn layui-btn-mini layui-btn-warm\" lay-event=\"open\">隐藏</a></td>";
            }
            if(is_array($v['son'])){
                foreach($v['son'] as $k1=>$v1){
                    $str .= "<tr><td class='visible-lg visible-md'>{$v1['cate_id']}</td>";
                    $str .= "<td class='text-left'>{$icon[1]}{$v1['name']}&nbsp;</td>";
                    $str .= "<td class='visible-lg visible-md'><img src='__PUBLIC__/{$v1['pic']}' alt=''></td><td class='visible-lg visible-md'><div class=\"layui-table-cell laytable-cell-1-sort\"> <input name=\"undefined\" data-id=\"undefined\" class=\"list_order layui-input\" value=\" {$v1['sort']}\" size=\"10\"> </div></td>";
                    if($v1['status'] == 1){
                        $str.="<td class='visible-lg visible-md'> <a class=\"layui-btn layui-btn-mini layui-btn-warm\" lay-event=\"open\">开启</a></td>";
                    }else{
                        $str.="<td class='visible-lg visible-md'><a class=\"layui-btn layui-btn-mini layui-btn-warm\" lay-event=\"open\">隐藏</a></td>";
                    }
                    if(is_array($v1['son'])){
                        foreach($v1['son'] as $k2=>$v2){
                            $str .= "<tr><td class='visible-lg visible-md'>{$v2['cate_id']}</td>";
                            $str .= "<td class='text-left'>{$icon[1]}{$icon[1]}{$v2['name']}&nbsp;</td>";
                            $str .= "<td class='visible-lg visible-md'><img src='__PUBLIC__/{$v2['pic']}' alt=''></td><td class='visible-lg visible-md'><div class=\"layui-table-cell laytable-cell-1-sort\"> <input name=\"undefined\" data-id=\"undefined\" class=\"list_order layui-input\" value=\" {$v2['sort']}\" size=\"10\"> </div></td>";
                            if($v['status'] == 1){
                                $str.="<td class='visible-lg visible-md'> <a class=\"layui-btn layui-btn-mini layui-btn-warm\" lay-event=\"open\">开启</a></td>";
                            }else{
                                $str.="<td class='visible-lg visible-md'><a class=\"layui-btn layui-btn-mini layui-btn-warm\" lay-event=\"open\">隐藏</a></td>";
                            }
                        }
                    }
                }
            }
        }*/

        //dump($categorys);

        $this->assign('icon', $icon);
        $this->assign('nbsp', $nbsp);
        $this->assign('list', $categorys);

        $this->assign('title','栏目列表');
        return $this->fetch();
    }

    public function add(){
        $icon = array('&nbsp;&nbsp;&nbsp;│  ', '├─ ', '&nbsp;&nbsp;&nbsp;&nbsp;└─ ');
        $nbsp = '&nbsp;&nbsp;&nbsp;';
        $catlsit = db('category')->field('cate_id,name,parent_id')->select();
        $tree = new Tree ($catlsit);
        $categorys = $tree->recursion(0);
         $str = "";
         foreach($categorys as $k=>$v){
            $str.="<option value='{$v['cate_id']}'>{$v['name']}</option>";
             if(is_array($v['son'])){
                 foreach($v['son'] as $k1=>$v1){
                     $str.="<option value='{$v1['cate_id']}'>$icon[1]{$v1['name']}</option>";
                     if(is_array($v1['son'])){
                         foreach($v1['son'] as $k2=>$v2){
                             $str.="<option value='{$v2['cate_id']}'>$icon[2]{$v2['name']}</option>";
                         }
                     }
                 }
             }
         }
        $this->assign('categorys', $str);
        $this->assign('title','添加类别');
        return $this->fetch();
    }

    public function insert(){
        $data = input('post.');
        $parent_id = input('parent_id');

        if($parent_id > 0 ){
            //通过父ID查找等级来判断添加的等级数和判断
            $level = db('category')->where('cate_id',$parent_id)->value('level');
            $data['level'] = $level+1;
        }else{
            $data['level'] = 1;
        }

        //如果大于三级将无法再添加
        if($data['level'] >3){
            $result['msg'] = '栏目添加失败,只能添加三级';
            $result['code'] = 0;
            return $result;
        }

        $row = db('category')->insert($data);
        $id = db('category')->getLastInsID();
        if($row) {
            //添加成功,修改一下家族路径
            if($parent_id > 0){   //如果大于0 就查询 path路径
                $path = db('category')->where('cate_id',$parent_id)->value('parent_id_path');
                $map['parent_id_path'] = $path.','.$id;
            }else{
                $map['parent_id_path'] =  $parent_id.','.$id;
            }
            db('category')->where('cate_id',$id)->update($map);
            $result['msg'] = '栏目添加成功!';
            $result['url'] = url('index');
            $result['code'] = 1;
            return $result;
        }else{
            $result['msg'] = '栏目添加失败!';
            $result['code'] = 0;
            return $result;
        }
    }

    public function edit(){
        if(request()->isPost()){
            $data = input('post.');
            $row = db('category')->update($data);
            if($row) {
                $result['msg'] = '修改成功!';
                $result['url'] = url('index');
                $result['code'] = 1;
                return $result;
            }else{
                $result['msg'] = '修改失败 !';
                $result['code'] = 0;
                return $result;
            }
        }else{
            $cate_id = input('cate_id');
            //查询当前修改的栏目信息
            $catInfo = db('category')->where('cate_id',$cate_id)->find();
            $this->assign('catInfo', $catInfo);
            $this->assign('title','修改类别');
            return $this->fetch();
        }
    }

    public function catUpdate(){
        $data = input('post.');
        $data['module'] = db('module')->where(array('id'=>$data['moduleid']))->value('name');
        if(!empty($data['readgroup'])){
            $data['readgroup'] = implode(',',$_POST['readgroup']);
        }else{
            $data['readgroup']='';
        }
        $data['arrparentid'] = $this->get_arrparentid($data['id']);
        $data['child'] = ($data['child']==1) ? '1' : '0';
        if (false !==db('category')->update($data)) {
            if($data['child']==1){
                $arrchildid = $this->get_arrchildid($data['id']);
                $data2['ismenu'] = $data['ismenu'];
                $data2['pagesize'] = $data['pagesize'];
                $data2['readgroup'] = $data['readgroup'];
                db('category')->where( ' id in ('.$arrchildid.')')->update($data2);
            }
            $this->repair();
            savecache('Category');
            $result['msg'] = '栏目修改成功!';
            cache('cate', NULL);
            $result['url'] = url('index');
            $result['code'] = 1;
            return $result;
        } else {
            $result['msg'] = '栏目修改失败!';
            $result['code'] = 0;
            return $result;
        }
    }


    public function repair() {
        @set_time_limit(500);
        $this->categorys = $categorys = array();
        $categorys =  $this->dao->where("parentid=0")->order('listorder ASC,id ASC')->select();
        $this->set_categorys($categorys);
        if(is_array($this->categorys)) {
            foreach($this->categorys as $id => $cat) {
                if($id == 0 || $cat['type']==1) continue;
                $this->categorys[$id]['arrparentid'] = $arrparentid = $this->get_arrparentid($id);
                $this->categorys[$id]['arrchildid'] = $arrchildid = $this->get_arrchildid($id);
                $this->categorys[$id]['parentdir'] = $parentdir = $this->get_parentdir($id);
                $this->dao->update(array('parentdir'=>$parentdir,'arrparentid'=>$arrparentid,'arrchildid'=>$arrchildid,'id'=>$id));
            }
        }
    }


    public function set_categorys($categorys = array()) {
        if (is_array($categorys) && !empty($categorys)) {
            foreach ($categorys as $id => $c) {
                $this->categorys[$c['id']] = $c;
                $r = $this->dao->where("parentid",$c['id'])->Order('listorder ASC,id ASC')->select();
                $this->set_categorys($r);
            }
        }
        return true;
    }

    public function get_arrparentid($id, $arrparentid = '') {
        if(!is_array($this->categorys) || !isset($this->categorys[$id])) return false;
        $parentid = $this->categorys[$id]['parentid'];
        $arrparentid = $arrparentid ? $parentid.','.$arrparentid : $parentid;
        if($parentid) {
            $arrparentid = $this->get_arrparentid($parentid, $arrparentid);
        } else {
            $this->categorys[$id]['arrparentid'] = $arrparentid;
        }
        return $arrparentid;
    }

    public function get_arrchildid($id) {
        $arrchildid = $id;
        if(is_array($this->categorys)) {
            foreach($this->categorys as $catid => $cat) {
                if($cat['parentid'] && $id != $catid) {
                    $arrparentids = explode(',', $cat['arrparentid']);
                    if(in_array($id, $arrparentids)){
                        $arrchildid .= ','.$catid;
                    }
                }
            }
        }
        return $arrchildid;
    }

    public function get_parentdir($id) {
        if($this->categorys[$id]['parentid']==0){
            return '';
        }
        $arrparentid = $this->categorys[$id]['arrparentid'];
        unset($r);
        if ($arrparentid) {
            $arrparentid = explode(',', $arrparentid);
            $arrcatdir = array();
            foreach($arrparentid as $pid) {
                if($pid==0) continue;
                $arrcatdir[] = $this->categorys[$pid]['catdir'];
            }
            return implode('/', $arrcatdir).'/';
        }
    }

    //删除栏目操作
    public function del() {
        $cate_id = input('param.id');

        //先删除其字栏目
        $sonList = db('category')->field('cate_id')->where('parent_id',$cate_id)->select();

        //查看有没有第三级,如果有就一层层的删
        if(is_array($sonList) && !empty($sonList)){
            //删除最未级
            foreach($sonList  as $k => $v){
                db('category')->where('parent_id',$v['cate_id'])->delete();
            }
            //删子级
            db('category')->where('parent_id',$cate_id)->delete();

            //删自己
            $row = db('category')->where('cate_id',$cate_id)->delete();
        }else{
            //删子级
            db('category')->where('parent_id',$cate_id)->delete();

            //删自己
            $row = db('category')->where('cate_id',$cate_id)->delete();
        }

        if($row > 0){
            $result['info'] = '栏目删除成功!';
            $result['url'] = url('index');
            $result['status'] = 1;
        }else{
            $result['info'] = '栏目删除失败!';
            $result['url'] = url('index');
            $result['status'] = 1;
        }

        return $result;
    }

    public function cOrder(){
        $data = input('post.');
        db('category')->update($data);
        $result = ['msg' => '排序成功！', 'code' => 1,'url'=>url('index')];
        return $result;
    }

    //修改栏目状态
    public function editStatus(){
        $data =  input('post.');
        if($data['status'] == 'false'){
            $map['status'] = 0;
            $row = db('category')->where('cate_id',$data['cat_id'])->update($map);
        }else{
            $map['status'] = 1;
            $row = db('category')->where('cate_id',$data['cat_id'])->update($map);
        }

        if($row > 0 ){
            $data  = array(
                'code' => 1,
                'msg'  =>  '修改成功',
                'url'  => url('index'),
            );
            return $data;
        }else{
            $data  = array(
                'code' => 0,
                'msg'  =>  '修改失败',
                'url'  => url('index'),
            );
            return $data;
        }

    }
}